/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable react/sort-comp */
/* eslint-disable react/jsx-no-bind */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import StationTree from '@/components/StationTree';
import StandardTable from '@/components/StandardTable';
import ConfiguraTion from '@/components/Configuration';
import { Button, Form, Input, Modal, message, Row, Col, Popconfirm, Popover } from 'antd';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { debounce, isEmpty } from 'lodash';
import ImportFiles from '@/components/ImportFiles';
import { formDownloadFile } from '@/utils/utils';
import question from '@/assets/question.svg';
import AsyncDownLoad from '@/components/DownloadBar/AsyncDownLoad';
import moment from 'moment';
import { triggerOpenGp } from '@/services/operator';
import TransformOperator from './components/TransformOperator';
import styes from './style.less';

const { confirm } = Modal;
const FormItem = Form.Item;

const importHelpURL = {
  yz: '//m.kuaidihelp.com/help/import_help',
  post: '//m.kuaidihelp.com/help/import_help_zy',
  yjy: '//m.kuaidihelp.com/help/import_help',
};

const RenderContent = ({ signKey }) => {
  const titleMap = {
    yz: '快递员APP',
    post: '中邮驿路APP',
    yjy: '驿加易APP',
  };
  return (
    <div>
      <p>
        待确认：新加的业务员默认为待确认，待确认状态的业务员无法开展任何业务，需要通知业务员至
        {titleMap[signKey]}
        -我的-个人信息内确认。
      </p>
      <p>
        已确认：在
        {titleMap[signKey]}
        -我的-个人信息内确认通过之后，状态变更为已确定，可以开展任何业务。
      </p>
      <p>
        已拒绝：在
        {titleMap[signKey]}
        -我的-个人信息内快递员拒绝加入，状态变更为已拒绝，无法开展任何业务。
      </p>
    </div>
  );
};

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleAdd,
    handleModalVisible,
    currentStation,
    currentOperator,
  } = props;
  const okHandle = () => {
    const { validateFields } = form;
    validateFields((err, fieldsValue) => {
      if (err) return;
      handleAdd({
        stationCode: currentStation.code,
        ...currentOperator,
        ...fieldsValue,
      });
    });
  };
  const title = currentOperator ? '编辑业务员' : '添加业务员';
  const { courier_name = '', courier_phone = '' } = currentOperator || {};
  const disabled = !!currentOperator;
  return (
    <Modal
      destroyOnClose
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      centered
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="姓名">
        {form.getFieldDecorator('courier_name', {
          initialValue: courier_name,
          rules: [
            {
              required: true,
              message: '请输入业务员姓名',
            },
            {
              pattern: /^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){2,20}$/,
              message: '请输入2-20位中文、英文或数字字符！',
            },
          ],
        })(<Input placeholder="请输入业务员姓名" />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label="手机号">
        {form.getFieldDecorator('courier_phone', {
          initialValue: courier_phone,
          rules: [
            {
              required: true,
              message: '请输入业务员手机号',
            },
            {
              pattern: /^1[2-9]{1}[0-9]{1}\d{8}$/,
              message: '手机号格式错误！',
            },
          ],
          validateTrigger: 'onBlur',
        })(<Input placeholder="请输入业务员手机号" disabled={disabled} />)}
      </FormItem>
    </Modal>
  );
});
@connect(({ loading, operator, station, user, configuration, setting, global }) => ({
  station,
  operator,
  user,
  configuration,
  hasAuthToChangeHtPwd: global.hasAuthToChangeHtPwd,
  checking: loading.effects['operator/deliveryStatus'],
  barSwitch: loading.effects['operator/quickStatus'],
  allowance: loading.effects['operator/allowanceCount'],
  modify: loading.effects['operator/modifyCount'],
  deleting: loading.effects['operator/deleteOperator'],
  submitting: loading.effects['operator/saveOperator'],
  getting: loading.effects['operator/getOperatorList'],
  batchDelete: loading.effects['operator/batchDelete'],
  globalOptions: setting.options,
}))
@Form.create()
export default class Operator extends PureComponent {
  state = {
    modalVisible: false,
    formValues: {},
    selectedRows: [],
    currentOperator: null,
    keyWords: '',
    uploadModalVisible: false,
    selectedSite: '',
    transformVisible: false,
  };

  handleSearch = debounce(
    e => {
      e && e.preventDefault();
      const { keyWords, formValues } = this.state;

      const params = {
        ...formValues,
        keyWords,
      };
      this.getOperatorList(params);
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    const { hasAuthToChangeHtPwd } = props;
    this.expandedRowKeys = hasAuthToChangeHtPwd ? ['yd', 'ht'] : ['yd'];
  }

  componentDidUpdate(prevPros) {
    const {
      station: { company_info },
      hasAuthToChangeHtPwd,
      dispatch,
    } = this.props;
    const old_company_info = prevPros.station.company_info;
    // 初次加载
    // 当左侧站点信息加载完再去请求右侧业务员列表信息
    if (!isEmpty(company_info) && old_company_info == null) {
      this.getOperatorList();
      // 更新默认展开的品牌
      hasAuthToChangeHtPwd &&
        dispatch({
          type: 'operator/updateState',
          payload: {
            expandedRowKeys: this.expandedRowKeys,
          },
        });
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'station/updateState',
      payload: {
        list: null, // 防止缓存
        company_info: null,
        selectedKeys: null,
        currentStation: null,
      },
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
      // `disabled`: true,
    });
  };

  getOperatorList = (params = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'operator/getOperatorList',
      payload: {
        ...params,
      },
    });
    this.setState({
      selectedRows: [],
    });
  };

  onSelect = (selectedSite, hasSearchOperator) => {
    const { dispatch } = this.props;
    this.pagination = {};
    this.setState({
      selectedRows: [],
      selectedSite,
    });
    if (!hasSearchOperator) {
      this.getOperatorList();
      dispatch({
        type: 'operator/updateState',
        payload: {
          expandedRowKeys: this.expandedRowKeys,
        },
      });
    }
  };

  handleStandardTableChange = pagination => {
    const { formValues } = this.state;
    const params = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
    };
    this.pagination = params;
    this.getOperatorList(params);
  };

  // 添加业务员
  handleModalVisible = (flag, currentOperator, selectId, modify) => {
    const { selectedRows } = this.state;
    const {
      station: { currentStation: currentStations },
      operator: { list },
    } = this.props;
    const id = selectId || '';
    if (modify == 'modify') {
      if (selectedRows.length <= 0) {
        message.error('请选择业务员');
      } else {
        if (id) {
          if (selectedRows.length > 1) {
            message.error('请选择一条数据进行操作');
            return;
          }
          for (let i = 0, len = list.length; i < len; i += 1) {
            const selectedOperator = list[i];
            if (selectedOperator.id == id) {
              currentOperator = list[i];
              break;
            }
          }
        }
        if (!currentStations) {
          message.error('请先选择站点');
          return;
        }
        this.setState({
          currentOperator,
          modalVisible: !!flag,
        });
      }
    } else {
      if (id) {
        if (selectedRows.length > 1) {
          message.error('请选择一条数据进行操作');
          return;
        }
        for (let i = 0, len = list.length; i < len; i += 1) {
          const selectedOperator = list[i];
          if (selectedOperator.id == id) {
            currentOperator = list[i];
            break;
          }
        }
      }
      if (!currentStations) {
        message.error('请先选择站点');
        return;
      }
      this.setState({
        currentOperator,
        modalVisible: !!flag,
      });
    }
  };

  showConfirm = params => {
    confirm({
      centered: true,
      okText: '确定',
      cancelText: '取消',
      title: '温馨提示',
      ...params,
    });
  };

  handleAdd = fields => {
    const { dispatch, user = {} } = this.props;
    const { currentUser = {} } = user;
    const { user_info = {} } = currentUser;
    const { user_type } = user_info;
    const isZyAccount = user_type == '2' || user_type == '3';
    const {
      station: { currentStation: currentSite },
    } = this.props;
    const { site_id: company_site_id, is_gp_area } = currentSite;
    const { id, courier_phone, courier_name, is_del } = fields;
    dispatch({
      type: 'operator/saveOperator',
      payload: id
        ? {
            courier_name,
            courier_phone,
            id,
            isZyAccount,
            is_del,
            area_id: is_gp_area == 2 ? company_site_id : undefined,
          }
        : {
            courier_name,
            courier_phone,
            company_site_id: company_site_id == -1 ? undefined : company_site_id, // 兼容主站点业务员添加
            isZyAccount,
            is_del,
            area_id: is_gp_area == 2 ? company_site_id : undefined,
          },
      then: ({ code, msg }) => {
        if (code == 0) {
          this.setState({ selectedRows: [] });
          this.handleModalVisible();
        } else if (code == 1060) {
          Modal.confirm({
            icon: () => <span />,
            width: 500,
            content: msg,
            okText: '是',
            cancelText: '否',
            onOk: () => this.handleAdd({ ...fields, is_del: 1 }),
            onCancel: () => this.handleModalVisible(),
          });
        }
      },
    });
  };

  // 批量删除
  handleBatchDelete = data => {
    const { dispatch } = this.props;
    const courierNo = [];
    data.forEach(v => {
      courierNo.push({
        courier_no: v.courier_no,
        status: v.status,
      });
    });
    if (data == '') {
      message.error('请选择业务员');
      return;
    }
    this.showConfirm({
      okText: '是',
      cancelText: '否',
      content: '是否删除业务员',
      onOk: () => {
        dispatch({
          type: 'operator/batchDelete',
          payload: courierNo,
        }).then(() => {
          this.setState({ selectedRows: [] });
        });
      },
    });
  };

  handleBlur = e => {
    this.setState({
      keyWords: e.target.value,
    });
  };

  showUploadModal = () => {
    const {
      station: { currentStation: currentStations },
    } = this.props;
    if (!currentStations) {
      message.error('请先选择站点');
      return;
    }
    this.setState({ uploadModalVisible: true });
  };

  hideUploadModal = () => {
    this.setState({ uploadModalVisible: false });
  };

  /**
   * 导出
   *  */
  onExport = debounce(
    () => {
      formDownloadFile('/v1/TotalDistribution/CourierBulletinBoard/courierListExport');
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  transformOperator() {
    const { selectedRows } = this.state;
    if (selectedRows.length === 0) {
      message.error('请选择业务员');
      return;
    }
    this.toggleTransformModal(true);
  }

  toggleTransformModal(visible) {
    this.setState({
      transformVisible: visible,
    });
  }

  reapply(phone, id) {
    const { dispatch } = this.props;
    dispatch({
      type: 'operator/reapply',
      payload: {
        phone,
        id,
      },
    }).then(() => {
      this.getOperatorList();
    });
  }

  handleOpenGp = (phone = [], is_disable) => {
    if (phone.length == 0) {
      message.error('请选择业务员');
      return;
    }
    triggerOpenGp({
      phone: phone
        .map(v => v.courier_phone)
        .filter(v => v)
        .join(','),
      is_disable,
    }).then(() => {
      this.getOperatorList(this.pagination);
    });
  };

  render() {
    const {
      getting = false,
      allowance = false,
      modify = false,
      submitting = false,
      deleting = false,
      operator: { list, pagination },
      station: { currentStation: currentSites },
      globalOptions: {
        key: signKey, // 区分是否是中邮账号
      },
      // user currentUser user_info
      user: { currentUser: { user_info: { realAccount } = {} } = {} } = {},
    } = this.props;
    // 假账号
    const fakeAccount = realAccount == 2;
    const {
      modalVisible,
      currentOperator,
      selectedRows,
      uploadModalVisible,
      selectedSite,
      transformVisible,
    } = this.state;
    const data = { list, pagination };
    const courierTitleMap = {
      yz: '快宝',
      post: '中邮',
      yjy: '驿加易',
    };
    const columns = [
      {
        title: `${courierTitleMap[signKey]}工号`,
        dataIndex: 'courier_no',
      },
      {
        title: '姓名',
        dataIndex: 'courier_name',
      },
      {
        title: '业务员手机号',
        dataIndex: 'courier_phone',
      },
      {
        title: () => (
          <div>
            状态
            {signKey !== 'post' && (
              <Popover
                content={<RenderContent signKey={signKey} />}
                title="状态解析"
                trigger="hover"
              >
                <img alt="" style={{ cursor: 'pointer', marginLeft: 5 }} src={question} />
              </Popover>
            )}
          </div>
        ),
        dataIndex: 'status',
        render: (status, record) => {
          switch (status) {
            case '已拒绝':
              return (
                <Row type="flex" gutter={[10, 0]}>
                  <Col>{status}</Col>
                  <Col>
                    <Popconfirm
                      placement="top"
                      title="是否确定重新申请？"
                      onConfirm={this.reapply.bind(this, record.courier_phone, record.id)}
                    >
                      <a>重新申请</a>
                    </Popconfirm>
                  </Col>
                </Row>
              );
            default:
              return status;
          }
        },
      },
      {
        title: '巴枪品牌',
        dataIndex: 'brand',
        render: brand => {
          const brands = brand.split('、');
          return fakeAccount ? brands.filter(v => !['圆通', '韵达'].includes(v)).join('、') : brand;
        },
      },
      {
        title: `${signKey == 'post' ? '中邮' : '快宝'}共配`,
        render: (code, record) => {
          const { status } = record;
          return (
            <Fragment>
              <ConfiguraTion
                disabled={status !== '已确认'}
                record={record}
                selectedSite={selectedSite}
              />
            </Fragment>
          );
        },
        dataIndex: 'courier_id',
      },
      {
        title: '共配状态',
        render: (is_disable, record) => {
          const { courier_phone } = record;
          const using = is_disable == 0;
          return (
            <Row type="flex" justify="space-between">
              <Col style={{ color: using ? '' : 'red' }}>{using ? '使用中' : '已禁用'}</Col>
              <Col>
                <a onClick={this.handleOpenGp.bind(this, [{ courier_phone }], using ? 1 : 0)}>
                  {using ? '禁用' : '启用'}
                </a>
              </Col>
            </Row>
          );
        },
        dataIndex: 'is_disable',
      },
    ];
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const time = moment()
      .format('YYYY-MM-DD')
      .split('-')
      .join('');
    return (
      <PageHeaderLayout title="业务员">
        <StationTree
          onSelect={(_selectedSite, hasSearch) => {
            this.onSelect(_selectedSite, hasSearch);
          }}
        >
          <Row className={styes['operator-button']} type="flex" justify="space-between">
            <Col style={{ marginBottom: 10 }}>
              <Button
                icon="plus"
                type="primary"
                style={{ marginRight: 8 }}
                onClick={() => this.handleModalVisible(true)}
              >
                添加业务员
              </Button>
              <ImportFiles
                visible={uploadModalVisible}
                onCancel={this.hideUploadModal}
                siteId={currentSites}
              >
                <Button type="primary" style={{ marginRight: 8 }} onClick={this.showUploadModal}>
                  批量导入
                </Button>
              </ImportFiles>
              <Button type="primary">
                <a
                  href={`https://upload.kuaidihelp.com/kb_citysite/courierexcel_module/业务员导入模板.xlsx?v=${time}`}
                >
                  下载导入模板
                </a>
              </Button>
              <Button
                type="primary"
                style={{ marginRight: 8 }}
                href={importHelpURL[signKey]}
                target="_blank"
              >
                导入帮助
              </Button>
              <AsyncDownLoad
                className={styes.exportButton}
                action="/v1/TotalDistribution/CourierBulletinBoard/courierListExport"
                method="POST"
              >
                <Button type="primary" style={{ marginRight: 8 }}>
                  导出
                </Button>
              </AsyncDownLoad>
              <Button
                type="primary"
                onClick={() => this.handleBatchDelete(selectedRows)}
                loading={deleting}
              >
                删除
              </Button>
            </Col>
            <Col style={{ textAlign: 'right' }}>
              <Row type="flex" justify="end" align="middle" gutter={[10, 0]}>
                <Col>业务员：</Col>
                <Col>
                  <Input
                    style={{ width: 260 }}
                    placeholder="请输入业务员手机或姓名进行搜索"
                    allowClear
                    onBlur={this.handleBlur}
                  />
                </Col>
                <Col>
                  <Button
                    type="primary"
                    icon="search"
                    onClick={this.handleSearch.bind(this)}
                    loading={getting}
                  >
                    查询
                  </Button>
                </Col>
              </Row>
            </Col>
          </Row>
          <div className={styes['operator-table']}>
            <StandardTable
              scroll={{ x: 900 }}
              rowKey="id"
              loading={getting || submitting || allowance || modify}
              data={data}
              columns={columns}
              selectedRows={selectedRows}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
              footer
            />
          </div>
          <div className={styes.modify}>
            <Row type="flex" justify="start">
              <Col className={styes.ml_20}>
                <a
                  onClick={() =>
                    this.handleModalVisible(true, selectedRows[0], selectedRows[0], 'modify')
                  }
                >
                  修改业务员
                </a>
              </Col>
              <Col className={styes.ml_20}>
                <TransformOperator
                  visible={transformVisible}
                  toggleOpen={this.toggleTransformModal.bind(this)}
                  getOperatorList={this.getOperatorList}
                  selectedOperator={selectedRows}
                >
                  <a onClick={this.transformOperator.bind(this)}>移动业务员</a>
                </TransformOperator>
              </Col>
              <Col className={styes.ml_20}>
                <a onClick={() => this.handleOpenGp(selectedRows, 1)}>禁用共配</a>
              </Col>
              <Col className={styes.ml_20}>
                <a onClick={() => this.handleOpenGp(selectedRows, 0)}>启用共配</a>
              </Col>
            </Row>
          </div>
        </StationTree>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          currentStation={currentSites}
          currentOperator={currentOperator}
        />
      </PageHeaderLayout>
    );
  }
}
